package com.boarsoft.message.test.activemq;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibm.mq.jms.MQConnectionFactory;

/**
 * 此类演示了如何使用ActiveMQ的客户端API，以短连接的方式来获取消息<br/>
 * 实际应用中应采用长连接方式，请参见Queue1Consumer1.java
 * 
 * @author Mac_J
 *
 */
public class AmqListenerTest1 {
	private static final Logger log = LoggerFactory.getLogger(AmqListenerTest1.class);

	public static void main(String[] args) throws JMSException {
//		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
//		// ActiveMQConnectionFactory factory = new
//		// ActiveMQConnectionFactory("http://localhost:8080?trace=true");
//		// JmsConnectionFactory factory = new
//		// JmsConnectionFactory("amqp://192.168.1.12:5672");
//		Connection connection = factory.createConnection("admin", "admin");
		MQConnectionFactory factory = new MQConnectionFactory();
		factory.setHostName("192.168.1.11");
		factory.setPort(1414);
		factory.setTransportType(1);
		factory.setCCSID(1208);
		factory.setQueueManager("test03");
		Connection connection = factory.createConnection();
		connection.start();
		final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Destination destination = session.createQueue("test03");
		Destination rd = session.createQueue("test04");
		final MessageConsumer consumer = session.createConsumer(destination);
		final MessageProducer rp = session.createProducer(rd);
		log.info("Waiting for messages...");
		while (true) {
			// 以文本或对象等方式获取消息内容
			javax.jms.TextMessage msg = (TextMessage) consumer.receive();
			String o = msg.getText();
			// 可以用任何形式对消息进行解析和处理
			// Message m = JsonUtil.parseObject(o, Message.class);
			// Object o = ((ObjectMessage) msg).getObject();
			// 此处可从spring容器中获取Queue1Consumer1的实例，并调用其put方法来处理消息
			// Map<String, RecipientStatus> rm = m.getRecipients();
			// for (String r : rm.keySet()) {
			// MessageService ms = (MessageSerivce)
			// applicationContext.getBean(r);
			// ms.put(m);
			// }
			log.info("Received text message {}", o);
//			Destination rd = msg.getJMSReplyTo();
//			MessageProducer rp = session.createProducer(rd);
//			try {
//				rp.send(session.createTextMessage("ok"));
//			} finally {
//				if (rp != null) {
//					try {
//						rp.close();
//					} catch (Exception e) {
//					}
//				}
//			}
			String id = msg.getJMSCorrelationID();
			TextMessage rm = session.createTextMessage("ok");
			rm.setJMSCorrelationID(id);
			rp.send(rm);
		}
	}
}